/**
 * 开源协议 GPL
 * 版权所有 吉安码动未来信息科技有限公司
 * 微信联系 zyprosoft
*/
import {
	refreshToken,
	login,
	qqLogin,
	baiduLogin,
	getUserInfoDetail
} from '@/api/api.js'

export function updateUserInfo() 
{
	getUserInfoDetail().then(res => {
		setUserInfo(res.data)
		uni.$emit('UserInfoBaseRefresh')
	}).catch(error => {
	})
}

export function wxCodeLogin() {
	uni.login({
		provider: 'weixin',
		success: function(res) {
			console.log('wxlogin:' + JSON.stringify(res))
			let errMsg = res.errMsg
			let code = res.code
			if (errMsg == 'login:ok' && code !== null && code !== '') {
				login(code).then(res => {
					setToken(res.data)
				}).catch(error => {

				})
			}
		},
		fail(error) {
			console.log('uni login fail:' + error)
		}
	})
}

export function qqCodeLogin() {
	uni.login({
		provider: 'qq',
		success: function(res) {
			console.log('qqlogin:' + JSON.stringify(res))
			let errMsg = res.errMsg
			let code = res.code
			if (errMsg == 'login:ok' && code !== null && code !== '') {
				qqLogin(code).then(res => {
					setToken(res.data)
				}).catch(error => {

				})
			}
		},
		fail(error) {
			console.log('uni login fail:' + error)
		}
	})
}

export function commonLogin() {
	console.log('login check start:')
	let token = getToken()
	if (token === null || token === undefined || token.length == 0) {
		console.log('no token start login!')
		// #ifdef MP-WEIXIN
		wxCodeLogin()
		// #endif
		// #ifdef MP-QQ
		qqCodeLogin()
		// #endif
		return
	}
	uni.checkSession({
		success() {
			console.log('session still effect!')
		},
		fail() {
			console.log('session expired!')
			// #ifdef MP-WEIXIN
			wxCodeLogin()
			// #endif
			// #ifdef MP-QQ
			qqCodeLogin()
			// #endif
			// #ifdef MP-BAIDU
			uni.navigateTo({
				url: '/pages/login/login'
			})
			// #endif
		}
	})
}

export function getToken() {
	try {
		// #ifdef MP-BAIDU
		let res = swan.getStorageSync('LoginUserToken')
		if (!(res instanceof Error)) {
			if (res) {
				console.log('getStorageSync success:', res);
				let decodeRes = JSON.parse(res)
				console.log('decode res:',decodeRes)
				return decodeRes.token
			} else {
				console.log('缓存找不到百度小程序下的Token');
			}
		} else {
			console.log('百度小程序读取Token失败')
		}
		// #endif
		// #ifndef MP-BAIDU
		let data = uni.getStorageSync('LoginUserToken')
		// #endif
		return data.token
	} catch (e) {
		console.log('fail get token:' + e)
		return null
	}
}

export function removeToken() {
	try {
		uni.removeStorageSync('LoginUserToken')
		console.log('remove user token success!')
	} catch (e) {
		console.log('fail remove user token:' + e)
	}
}

export function isLogin() {
	let userInfo = getUserInfo()
	let userInfoEmpty = userInfo === null || userInfo === undefined || userInfo === ""
	if (userInfoEmpty) {
		return false
	}
	return userInfo.mobile !== null && userInfo.mobile !== undefined && userInfo.mobile !== ""
}

export function logout() {
	try {
		uni.removeStorageSync('LoginUserInfo')
		return true
	} catch (e) {
		//TODO handle the exception
		return false
	}
}

export function tokenRefreshIfNeed() {
	let data = getToken()
	console.log('get token:' + JSON.stringify(data))

	// #ifdef MP-WEIXIN
	//微信token是否将要过期
	if (data !== null && data.wx_token_expire !== null) {
		let wxTokenExpire = data.wx_token_expire
		console.log('wx token expire:' + wxTokenExpire)
		let now = parseInt(new Date().getTime() / 1000);
		if (wxTokenExpire - now < 60 * 60 * 24) {
			console.log('微信Token将在一天内过期，开始刷新')
			uni.login({
				success(res) {
					console.log(res);
					console.log('wxlogin:' + JSON.stringify(res))
					let errMsg = res.errMsg
					let code = res.code
					if (errMsg == 'login:ok' && code !== null && code !== '') {
						login(code).then(res => {
							setToken(res.data)
						}).catch(error => {

						})
					}
				}
			});
			return
		} else {
			let passTime = (wxTokenExpire - now) / (60 * 60 * 24)
			console.log("微信token还未到刷新日期,剩余" + passTime + '天')
		}
	}
	// #endif

	//百度和QQ没有用token做事情，可以不用刷新Token,只刷新应用Token即可
	if (data !== null && data.token_expire !== null) {
		let tokenExpire = data.token_expire
		//检查是否将要过期，主动刷新token
		let now = parseInt(new Date().getTime() / 1000);
		if (tokenExpire - now < 60 * 60 * 24) {
			console.log('用户Token将在一天内过期，开始刷新')
			refreshToken().then(res => {
				setToken(res.data)
				console.log('用户Token刷新成功')
			}).catch(error => {
				console.log('refresh token fail')
			})
		} else {
			let passTime = (tokenExpire - now) / (60 * 60 * 24)
			console.log("应用token还未到刷新日期,剩余" + passTime + '天')
		}
	}
}

export function setToken(token) {
	try {
		console.log('save token:')
		console.log(token)
		// #ifdef MP-BAIDU
		let stringToken = JSON.stringify(token)
		let res = swan.setStorageSync('LoginUserToken', stringToken)
		if (!(res instanceof Error)) {
			console.log('存储百度Token成功')
		} else {
			console.log('存储百度Token失败')
		}
		// #endif
		// #ifndef MP-BAIDU
		uni.setStorageSync('LoginUserToken', token)
		// #endif
		return true
	} catch (e) {
		console.log('fail set token:' + e)
		return false
	}
}

export function setUserInfoTimestamp() {
	try {
		console.log('save user info timestamp')
		let timestamp = parseInt(new Date().getTime() / 1000)
		console.log(timestamp)
		uni.setStorageSync('LoginUserInfoTimestamp', timestamp)
		return true
	} catch (e) {
		console.log('fail set user info timestamp:' + e)
		return false
	}
}

export function getUserInfoTimestamp() {
	try {
		let timestamp = uni.getStorageSync('LoginUserInfoTimestamp')
		console.log('get user info timestamp:' + JSON.stringify(timestamp))
		return timestamp
	} catch (e) {
		console.log('fail get user info timestamp:' + e)
		return null
	}
}

export function setUserInfo(userInfo) {
	try {
		console.log('save user info')
		console.log(userInfo)
		uni.setStorageSync('LoginUserInfo', userInfo)
		return true
	} catch (e) {
		console.log('fail set user info:' + e)
		return false
	}
}

export function getUserInfo() {
	try {
		let userInfo = uni.getStorageSync('LoginUserInfo')
		console.log('get user info:' + JSON.stringify(userInfo))
		return userInfo
	} catch (e) {
		console.log('fail get user info:' + e)
		return null
	}
}

//保存系统设置信息
export function saveAppSettingInfo(info) {
	try {
		console.log('save setting info')
		console.log(info)
		uni.setStorageSync('AppSettingInfo', info)
		return true
	} catch (e) {
		console.log('fail set AppSettingInfo info:' + e)
		return false
	}
}

//获取系统设置信息
export function getAppSettingInfo() {
	try {
		let settingInfo = uni.getStorageSync('AppSettingInfo')
		console.log('get AppSettingInfo:' + JSON.stringify(settingInfo))
		return settingInfo
	} catch (e) {
		console.log('fail get AppSettingInfo:' + e)
		return null
	}
}

//保存订单展示设置
export function saveOrderShowSetting(status) {
	try {
		console.log('save setting info')
		console.log(status)
		uni.setStorageSync('OrderShowSetting', status)
		return true
	} catch (e) {
		console.log('fail set OrderShowSetting info:' + e)
		return false
	}
}

//获取订单内容显示设置,默认精简模式关闭
export function getOrderShowSetting() {
	try {
		let status = uni.getStorageSync('OrderShowSetting')
		if (status === null || status === undefined) {
			return false
		}
		console.log('get OrderShowSetting:' + JSON.stringify(status))
		return status
	} catch (e) {
		console.log('fail get OrderShowSetting:' + e)
		return null
	}
}

export function getReportTipReadStatus() {
	try {
		let status = uni.getStorageSync('ReportTipReadStatus')
		if (status === null || status === undefined || status.length == 0) {
			console.log('ReportTipReadStatus not exist')
			return false
		}
		console.log('get ReportTipReadStatus:' + JSON.stringify(status))
		return true
	} catch (e) {
		console.log('fail get ReportTipReadStatus:' + e)
		return null
	}
}

export function setReportTipFinishRead() {
	try {
		console.log('save setting info')
		uni.setStorageSync('ReportTipReadStatus', '1')
		return true
	} catch (e) {
		console.log('fail set ReportTipReadStatus info:' + e)
		return false
	}
}
